<template>
  <!-- 资源目录配置 -->
  <el-card class="app-container">
    <el-row>
      <!--部门数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-tree
            ref="writTree"
            :data="treeData"
            node-key="id"
            :highlight-current="true"
            :props="defaultProp"
            class="treeStyle"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
            @node-drop="handleDrop"
            :default-expanded-keys="defaultShowNodes"
            draggable
          >
            <span
              class="custom-tree-node"
              slot-scope="{ node, data }"
              @mouseleave="mouseleave(data, $event)"
            >
              <span
                class="nodeStyle"
                @click="singleClick(data)"
                @mouseover="mouseover(data, $event)"
              >
                <i :class="data.icon" style="margin-right: 5px"></i>
                {{ node.label }}
              </span>
              <span class="none black" style="zindex: 100">
                <i @click="() => append(data, node)" class="el-icon-plus" title="新增"></i>
                <i
                  v-if="data.id !== 0"
                  @click="() => remove(node, data)"
                  class="el-icon-delete"
                  title="删除"
                ></i>
                <i
                  v-if="data.id !== 0"
                  @click="() => rename(node, data)"
                  class="el-icon-edit"
                  title="编辑"
                ></i>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :xs="24">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="first">
            <!-- 新增 -->
            <formModal/>
          </el-tab-pane>
          <el-tab-pane label="关联地图服务" name="second">
            <div>
              <Transfer/>
              <div class="saveBtn">
                <el-button type="primary" @click="saveData()">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="关联三维模型" name="third">
            <div>
              <Transfer/>
              <div class="saveBtn">
                <el-button type="primary" @click="saveData()">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="关联文件" name="fourth">
            <div>
              <Transfer/>
              <div class="saveBtn">
                <el-button type="primary" @click="saveData()">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog title="选择图标" v-model="iconDialog">
      <ul class="iconList">
        <li
          v-for="(item, index) in iconList"
          :class="{ active: active === index }"
          :key="index"
          @click="changeIcon(index, item)"
        >
          <i :class="item.value" :title="item.label"></i>
        </li>
      </ul>
      <div class style="text-align: center">
        <el-button type="primary" @click="sure()">确定</el-button>
      </div>
    </el-dialog>
    <div class="footer">
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { getToken } from '@/utils/auth'
import getListData from '@/utils/formatTree'
import Transfer from '@/components/Transfer/index.vue'
import formModal from './formModal.vue'
export default {
    name: 'User',
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: {Transfer,formModal},
    data() {
        return {
            totalData: [],
            linkData: [],

            linkId: '',
            iconName: '',
            defaultShowNodes: [], // 这里存放要默认展开的节点 id
            active: '',
            iconDialog: false,
            activeName: 'first',
            addObj: {},
            defaultProp: {
                label: 'contentsName',
                id: 'id',
                pid: 'pid',
            },
            cityOptions: [],
            selectData: '',
            treeData: [],
            addDialog: false,

            // 表单参数
            form: {},
            defaultProps: {
                children: 'children',
                label: 'label',
            },

            isMenuList: [
                {
                    label: '同级节点',
                    value: 1,
                },
                {
                    label: '子级节点',
                    value: 2,
                },
            ],

            // 表单校验
            rules: {},
            ruleForm: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            mrzyList: [
                {
                    label: '是',
                    value: 1,
                },
                {
                    label: '否',
                    value: 0,
                },
            ],
            typeList: [
                {
                    label: 'map',
                    value: 1,
                },
                {
                    label: 'file',
                    value: 2,
                },
            ],
            addForm: {
                pid: '',
                contentsName: '新建目录',
                jdNode: '',
                isValid: 1,
                isAttach: 1,
                isDefaultResource: 1,
                dataType: 1,
                icon: '',
            },
            addRules: {
                jdNode: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
                contentsName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
                isValid: [{ required: true, message: '请选择是否有效', trigger: 'change' }],
                icon: [
                    {
                        required: true,
                        message: '请选择图标',
                    },
                ],
                isAttach: [
                    {
                        required: true,
                        message: '请选择是否有附件按钮',
                        trigger: 'change',
                    },
                ],
                isDefaultResource: [
                    {
                        required: true,
                        message: '请选择是否为默认资源',
                        trigger: 'change',
                    },
                ],
                dataType: [
                    {
                        required: true,
                        message: '请选择打开的数据类型',
                        trigger: 'change',
                    },
                ],
            },
            editForm: {
                pid: '',
                contentsName: '',
                isValid: '',
                icon: '',
                isAttach: '',
                isDefaultResource: '',
                dataType: '',
                createTime: '',
                updateTime: '',
            },
            editRules: {
                contentsName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
                isValid: [{ required: true, message: '请选择是否有效', trigger: 'change' }],
                isAttach: [
                    {
                        required: true,
                        message: '请选择是否有附件按钮',
                        trigger: 'change',
                    },
                ],
                isDefaultResource: [
                    {
                        required: true,
                        message: '请选择是否为默认资源',
                        trigger: 'change',
                    },
                ],
                icon: [
                    {
                        required: true,
                        message: '请选择图标',
                        trigger: 'change',
                    },
                ],
                dataType: [
                    {
                        required: true,
                        message: '请选择打开的数据类型',
                        trigger: 'change',
                    },
                ],
            },
            operaType: '', //1 新增  2 编辑
            iconList: [
                {
                    label: '图层',
                    value: 'iconfont icon-layer',
                },
                {
                    label: '图表二',
                    value: 'iconfont icon-zhankai',
                },
                {
                    label: '文件夹',
                    value: 'iconfont icon-wenjianjia',
                },
            ],
        }
    },
    // 默认认展开一级
    watch: {
        treeData: {
            handler() {
                this.treeData.forEach(item => {
                    this.defaultShowNodes.push(item.id)
                })
            },
            immediate: true,
        },
    },

    created() {
        this.getTreeData()
    },
    methods: {
        // 树节点展开
        handleNodeExpand(data) {
            // 保存当前展开的节点
            let flag = false
            this.defaultShowNodes.some(item => {
                if (item === data.id) {
                    // 判断当前节点是否存在， 存在不做处理
                    flag = true
                    return true
                }
            })
            if (!flag) {
                // 不存在则存到数组里
                this.defaultShowNodes.push(data.id)
            }
        },
        // 树节点关闭
        handleNodeCollapse(data) {
            this.defaultShowNodes.some((item, i) => {
                if (item === data.id) {
                    // 删除关闭节点
                    this.defaultShowNodes.length = i
                }
            })
        },
        // 获取关联地图服务的所有数据
        getLinkList() {
            getLinkList().then(res => {
                if (res.code == '200') {
                    this.totalData = res.rows
                }
            })
        },
        // 已关联数据
        getLinkData(data) {
            getLinkData(data).then(res => {
                if (res.code == '200') {
                    this.linkData = res.data
                }
            })
        },
        // 保存关联数据
        saveData() {
            let ids
            if (this.linkData.length == 0) {
                ids = '0'
            } else {
                ids = this.linkData
                    .map(item => {
                        return item
                    })
                    .join(',')
            }
            postLinkData(this.linkId, ids).then(res => {
                if (res.code == '200') {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                    })
                }
            })
        },
        handleClick(tab, event) {},
        addIcon() {
            this.iconDialog = true
        },
        changeIcon(index, data) {
            this.active = index
            this.iconName = data.value
        },
        // 图标选择确定事件
        sure() {
            this.iconDialog = false
            this.active = ''
        },

        // 新增保存
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.addForm.jdNode == '1') {
                        this.addForm.pid = this.addObj.pid
                    } else {
                        this.addForm.pid = this.addObj.id
                    }
                    var params = {
                        pid: this.addForm.pid,
                        contentsName: this.addForm.contentsName,
                        icon: this.iconName,
                        isValid: this.addForm.isValid,
                        isAttach: this.addForm.isAttach,
                        isDefaultResource: this.addForm.isDefaultResource,
                        dataType: this.addForm.dataType,
                    }
                    // addMenu(params).then((res) => {
                    //   if (res.code == "200") {
                    //     this.$message({
                    //       message: res.msg,
                    //       type: "success",
                    //     });
                    //     this.iconName = "";
                    //     this.addForm.contentsName = "新建目录";
                    //     this.$refs.addForm.resetFields();
                    //     this.addForm.jdNode = "";
                    //     this.getTreeData();
                    //   }
                    // });
                } else {
                    return false
                }
            })
        },
        // 编辑保存
        editsubmitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    var params = {
                        pid: this.editForm.pid,
                        contentsName: this.editForm.contentsName,
                        isValid: this.editForm.isValid,
                        icon: this.iconName == '' ? this.editForm.icon : this.iconName,
                        isAttach: this.editForm.isAttach,
                        isDefaultResource: this.editForm.isDefaultResource,
                        dataType: this.editForm.dataType,
                        createTime: this.editForm.createTime,
                        updateTime: this.editForm.updateTime,
                        id: this.editForm.id,
                    }
                    // editMenu(params).then((res) => {
                    //   if (res.code == "200") {
                    //     this.$message({
                    //       message: res.msg,
                    //       type: "success",
                    //     });
                    //     this.getTreeData();
                    //     this.iconName = "";
                    //   }
                    // });
                } else {
                    return false
                }
            })
        },
        // 重置
        addResetForm(formName) {
            this.$refs[formName].resetFields()
        },
        editResetForm(formName) {
            this.addDialog = false
        },
        // 获取目录
        getTreeData() {
            // getMenuList().then((res) => {
            //   this.treeData = res.rows;
            //   this.formatTreeData();
            // });
        },
        // 目录格式转换
        formatTreeData() {
            this.treeData = getListData(this.treeData, 0, this.defaultProp)
        },
        mouseleave(data, $event) {
            $event.currentTarget.firstElementChild.nextElementSibling.setAttribute('class', 'nodeSame none')
        },
        mouseover(data, $event) {
            $event.currentTarget.nextElementSibling.setAttribute('class', 'nodeSame block')
        },
        //添加节点
        append(data) {
            this.activeName = 'first'
            this.operaType = '1'
            this.addObj = data
            // this.addForm = data;
            // console.log(data.id, "新增操作");
            // this.styleType = "add";
            // this.addDialog = true;
            // this.addObj = data;
            // this.addForm.pid = data.id;
            // this.addForm.pid = data.id;

            // const newChild = { id: id++, title: "未命名", children: [] };
            // if (!data.children) {
            //   this.$set(data, "children", []);
            // }
            // data.children.push(newChild);
        },
        // 删除节点
        remove(node, data) {
            this.$confirm('确认删除该节点' + data.contentsName + '吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    // deleteMenu(data.id).then((res) => {
                    //   if (res.code == "200") {
                    //     this.$message({
                    //       message: res.msg,
                    //       type: "success",
                    //     });
                    //     this.getTreeData();
                    //   }
                    // });
                })
                .catch(() => {})
        },
        //拖拽成功完成时触发的事件,，在这里可以将节点拖拽后的顺序返给后端
        handleDrop(draggingNode, dropNode, dropType, event) {
            console.log('我拖拽成功了')
            console.log('dropType: ', dropType)
            console.log('draggingNode: ', draggingNode)
            console.log('dropNode: ', dropNode)
            var paramData = []
            // 当拖拽类型不为inner,说明只是同级或者跨级排序，只需要寻找目标节点的父ID，获取其对象以及所有的子节点，并为子节点设置当前对象的ID为父ID即可
            // 当拖拽类型为inner，说明拖拽节点成为了目标节点的子节点，只需要获取目标节点对象即可
            var data = dropType != 'inner' ? dropNode.parent.data : dropNode.data
            var nodeData = dropNode.level == 1 && dropType != 'inner' ? data : data.children
            // 设置父ID,当level为1说明在第一级，pid为0
            nodeData.forEach(element => {
                element.pid = dropNode.level == 1 ? 0 : data.id
            })
            nodeData.forEach((element, i) => {
                var collection = {
                    collectionId: element.id,
                    parentId: element.pid,
                    sort: i + 1,
                }
                paramData.push(collection)
            })

            this.loading = true
            console.log(paramData, 'paramData')
            // updateCollection(JSON.stringify(paramData)).then(response => {
            //     this.msgSuccess("排序成功");
            //     this.loading = false;
            //     });
        },

        // 编辑节点
        rename(node, data) {
            this.activeName = 'first'
            this.operaType = '2'
            this.editForm = data
        },
        // 关联地图服务
        handleChange(value, direction, movedKeys) {},

        // 筛选节点
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.activeName = 'second'
            this.getLinkList()
            this.linkId = data.id
            this.getLinkData(data.id)

            // this.queryParams.deptId = data.id;
            // this.getList();
        },
        singleClick(data) {
            this.activeName = 'second'
            this.getLinkList()
            this.linkId = data.id
            this.getLinkData(data.id)
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                userId: undefined,
                deptId: undefined,
                userName: undefined,
                nickName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: '0',
                remark: undefined,
                postIds: [],
                roleIds: [],
            }
            this.resetForm('form')
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const userIds = row.userId || this.ids
            this.$modal
                .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
                .then(function() {
                    return delUser(userIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
    },
}
</script>

<style lang="less" scoped>
.app-container {
    position: relative;
    width: 97.5%;
    height: 83%;
    bottom: 50px;
    left: 0px;
    box-sizing: border-box;
    overflow: hidden;
    background: #fcfcfc;
}
.footer {
    position: fixed;
    bottom: 100px;
    left: 17.25%;
    width: 81.1%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 50px;
    background: #fff;
    z-index: 99;
    .dialog-footer {
        margin-right: 40px;
    }
}
:deep(.el-tabs__item) {
    font-size: 16px;
}
:deep(.el-transfer-panel) {
    width: 400px;
    height: 500px;
}
:deep( .el-transfer-panel__list.is-filterable) {
    height: 400px;
}
:deep(.el-tabs__nav-scroll) {
    margin-left: 20px;
}
</style>
